package com.annotation;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.integration.redis.util.RedisLockRegistry;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;

/**
 * @author ben.huang
 */
@Component
@Aspect
@Slf4j
public class AntiReplayAspect {
    @Resource
    private RedisLockRegistry redisLockRegistry;

    @Pointcut("@annotation(antiReplay)")
    public void pointcut(AntiReplay antiReplay){

    }

    @Around(value = "pointcut(antiReplay)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint,AntiReplay antiReplay) throws Throwable{
        int tryLockTime = antiReplay.tryLockTime();
        Object result = null;
        String name = "testRedisLock-";
        String path = antiReplay.key();
        String key = name + path;
        Lock lock = redisLockRegistry.obtain(key);
        boolean isSuccess = lock.tryLock(tryLockTime, TimeUnit.MILLISECONDS);
        if(isSuccess){
            log.info("获取锁 key = [{}]",key);
            try{
                result = proceedingJoinPoint.proceed();
            }
            finally{
                if(isSuccess){
                    lock.unlock();
                    log.info("释放锁 success, key = [{}]",key);
                }
            }
        }
        else{
            log.info("获取锁失败 fial ,key = [{}]",key);
            throw new Exception("error");
        }
        return result;
    }
}
